package com.lry.web.cartoon.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.lry.web.cartoon.service.CartoonContentService;
import com.lry.web.rests.LoadingCacheService;
import com.lry.web.util.IPUtil;
import com.lry.web.util.Result;
import com.lry.web.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/cartoonContent")
public class CartoonContentController {
    @Autowired
    CartoonContentService cartoonContentService;
    @Autowired
    LoadingCacheService loadingCacheService;

    //内容阶段
    @RequestMapping("/search/{chapterId}")
    @ResponseBody
    public Result contentSearch(HttpServletRequest request,@PathVariable(value = "chapterId") String chapterId) throws IOException {
        String ipAddr = IPUtil.getIpAddr(request);
        try {
            RateLimiter limiter = loadingCacheService.getRateLimiter(ipAddr);
            if(limiter.tryAcquire()){
                Map<String, Object> cartoonContent = cartoonContentService.getCartoonContent(chapterId);
                if(((List<String>)cartoonContent.get("content")).size()==0){
                    return ResultUtil.error(1,"没有查询到相关数据！");
                }
                Map<String, Object> listMap = new HashMap<String, Object>();
                int sizes = 1;
                listMap.put("count",sizes);
                listMap.put("data",cartoonContent);
                return ResultUtil.success(listMap);
            }else {
                return ResultUtil.error(2,"请求过于频繁");
            }
        } catch (ExecutionException e) {
            return ResultUtil.error(1,"系统错误");
        }


    }
}
